<template>
   <div>
       <!-- 抽屉框 -->
       <el-drawer 
		    class="el-drawer__wrapper"
		    title="添加栏目" 
			ref="drawer" 
			:visible.sync="roleCountDrawer" 
			:append-to-body="true"  
			:modal-append-to-body="true"
			direction="rtl" 
			:before-close="beclose"
			:with-header="false"
			:wrapperClosable="false"
		> 
            <!-- 头部 -->
            <div class="flex-box drawerHeader" style="border-bottom: 1px solid #888; display: flex;justify-content: space-between; align-items: center; padding:  0 20px;">
				<span class="header-text">添加栏目</span>
				<el-button
					@click="beclose"
					type="text"
					class="el-dialog__close el-icon el-icon-close"
					style="border: none;cursor: pointer;font-size: 20px;color: inherit;"
				>
				</el-button>
			</div>
            <!-- 搜索区域 -->
			<div style="width: 100%; padding: 20px;">
				<el-input
					placeholder="可搜索报表名称、编号、说明"
					prefix-icon="el-icon-search"
					v-model="statement"
					:clearable="true"
					@clear="getTree"
					@keyup.enter.native="search"
				>
				</el-input>
                <div class="toolbar">
                   <div class="toolbar_left">
                        <el-popover
                            placement="bottom"
                            trigger="click"
                            width="275"
                            v-model="visible"
                        >
                            <el-input
                                slot="reference"
                                :placeholder="placeholder"
                                v-model="selectWorkName"
                                @focus="clearSelectWorkName"
                                @keyup.enter.native="findOrg"
                            >
                            </el-input>
                            <div style="width: 100%;">
                                <vxe-table
                                    ref="grid"
                                    width="auto"
                                    resizable
                                    row-id="id"
                                    auto-resize
                                    border="none"
                                    max-height="300px"
                                    :show-header="false"
                                    :cell-class-name="cellClassName"
                                    :radio-config="{labelField: 'name', checkStrictly: true, checkRowKey: defaultSelecteRow, reserve:true}"
                                    :tree-config="{children: 'children', hasChild: 'children'}"
                                    :data="workTree"
                                    @radio-change="changeCheckBox"
                                >
                                    <vxe-table-column type="radio" tree-node></vxe-table-column>
                                </vxe-table>
                            </div>
                        </el-popover>
                   </div>
                   <div class="toolbar_right">
                       	<el-select v-model="value" placeholder="请选择" size="medium" @change="switchType" style="width:100%;height:40px;">
                           <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
                           </el-option>
						</el-select>
                   </div>
                </div>
			</div>
            <!-- 中部树区域  @checkbox-change="changeOrgCheckBox"  reportDtoList childrenSortList

                :tree-config="{lazy: true, transform: true, children: 'childrenSortList', hasChild: 'childrenSortList', loadMethod: loadChildrenMethod}"
			    :checkbox-config="{labelField: 'name'}"
            -->
			<div style="height:calc(100vh - 260px);">
				<vxe-table
					v-loading="reportLoad"
					ref="xTree"
					auto-resize
                    row-key
                    show-overflow
					height="auto"
                    keep-source
                    class="mytable-style form-scrollbar font-color-black"
					row-id="id"
                    highlight-current-row
					highlight-hover-row
					:data="tableData"
                    :show-header="false"
                    :tree-config="{transform: true, rowField: 'id', parentField: 'parentId'}" 
                    :checkbox-config="{labelField: 'id'}" 
					:empty-render="{name: 'NotDataTips'}"
                    @checkbox-change="TreeChangeCheckBox"
				>
					<vxe-table-column tree-node type="checkbox" field="name">
                        <template #default="{row}">
                             <span>
                                <template v-if="row.children.length > 0">
                                    <i :class="$refs.xTree.isTreeExpandByRow(row) ? 'el-icon-folder-opened' : 'el-icon-folder'" style="color:#32A3DF;font-size:18px;"></i>
                                </template>
                                <template v-if="row.children.length <= 0"> 
                                    <i class="el-icon-document" style="color:#32A3DF;font-size:18px;"></i>
                                </template>
                                <span>{{row.name}}</span>
                             </span>                           
                        </template>
                    </vxe-table-column>
				</vxe-table>	
			</div>
            <!-- 底部按钮区域 -->
			<div class="flex-box">
				<div style="margin: 20px auto; display: flex; justify-content:center; align-items:center;">
					<el-button style="width:230px;" type="primary" :disabled="isInProgress" @click="confirmButton">{{isInProgress?'确定中':'确定'}}</el-button>
					<el-button style="width:230px;"  @click="beclose">取 消</el-button>
				</div>
			</div>
	   </el-drawer>
   </div>
</template>

<script>

export default {
      name: 'AddColumn',
      props: {
          propsObj: {
              type: Object    //角色id  查询类型
          }
      },
      data(){
          return {
                roleCountDrawer: true,	 //是否显示抽屉
                reportLoad: false,       //树加载效果
                isInProgress: false,    //确定按钮是否禁用
                tableData: [],         //树数组
                statement: "",         //搜索内容
                usersList:[],           //已选中的数据
                removeUserList:[],      //取消选中删除的数据
                selectAddListOff: [],    //已添加的报表id
                closeList: [],         //删除报表的id数组
                parentList:[],           //添加报表栏目父级id
                parentCloseList: [],   //删除父级报表栏目id
                selectRecordsList: [],    //初始进来获取全部已勾选的行

                selectWorkName: "",       //单位搜索
                visible: false,           //控制弹出框关闭
                placeholder: '',          //单位输入框提示语
                defaultSelecteRow: null,  //默认选中id
                rowid: null,              //默认进来的单位id
				companyid: null,          //单位id
                workTree: [], 		      //单位树数组
                selectWorkList: [], 	  //选中的单位
				selectWorkName: '', 	  //选中的单位名称
                workDataSource: [],       //单位数据源
                isFull: true,
                value: '4',				//类型
            	options: [              //期号
					{name: '年报',id: '1'},
					{name: '半年报',id:'2'},
					{name: '季报',id: '3'},
					{name: '月报',id: '4'},
					{name: '旬报',id: '5'},
					{name: '周报',id: '6'},
					{name: '日报',id: '7'},
				],
                closeList:[],            //存储父级取消的数据  
                selectAll: []            //存储父级选中的数据
          }
      },
       created(){
        this.getTree()
      },
      computed: {
        checkRowKeys() {
            let arr = [];
            for(let i=0; i<this.usersList.length; i++) {
                arr.push(this.usersList[i].id);
            }
            return arr;
        }
	  },
      mounted(){
      },
      methods: {
			// 关闭弹框
			closeAddReportDrawer(){
				this.roleCountDrawer = false;
			},
            // 取消
			beclose(){
				this.$emit('closeAddReportDrawer');
			},
            // 搜索
            search(){
                const content = this.statement
                if (content == '' || null) {
                    this.getTree()
                }else{
                    this.statement = content;
                    this.getTree()
                }
            },
            // 获取栏目树
            getTree(){
                this.reportLoad = true;
                this.tableData = [];
                const list = [
                    { 
                        id: 1,
                        name: '第一层01',
                        childrenSortList: [],
                        reportDtoList: [
                            { id: 217, name: '人员17'},
                            { id: 218, name: '人员18'},
                        ],
                    },
                    {
                        id: 2, 
                        name: '第一层02',
                        childrenSortList: [    // 2
                            {  
                            id: 11,      
                            name: '第二层1',  
                            childrenSortList: [       // 5
                                {
                                id: 101,
                                childrenSortList: [],
                                name: '单位1',
                                reportDtoList: [
                                    { 
                                    id: 201,
                                    name: "人员1"
                                    },
                                    { 
                                    id: 202,
                                    name: "人员2"
                                    },
                                    { 
                                    id: 203,
                                    name: "人员3"
                                    },
                                    { 
                                    id: 204,
                                    name: "人员4"
                                    },
                                    { 
                                    id: 205,
                                    name: "人员5"
                                    },
                                    { 
                                    id: 206,
                                    name: "人员6"
                                    },
                                ]
                                },
                                {
                                id: 102,
                                childrenSortList: [],
                                name: '单位2',
                                reportDtoList: [
                                    { 
                                    id: 207,
                                    name: "人员7"
                                    },
                                    { 
                                    id: 208,
                                    name: "人员8"
                                    },
                
                                ]
                                },   
                            ],
                            reportDtoList:[]
                            },
                            {  
                            id: 12,      
                            name: '第二层2',  
                            childrenSortList: [       // 5
                                {
                                id: 103,
                                childrenSortList: [],
                                name: '单位3',
                                reportDtoList: [
                                    { 
                                    id: 209,
                                    name: "人员9"
                                    },
                                    { 
                                    id: 210,
                                    name: "人员10"
                                    },
                                    { 
                                    id: 211,
                                    name: "人员11"
                                    }
                                ]
                                },
                                {
                                id: 104,
                                childrenSortList: [],
                                name: '单位4',
                                reportDtoList: [
                                    { 
                                    id: 212,
                                    name: "人员12"
                                    },
                                    { 
                                    id: 213,
                                    name: "人员13"
                                    },
                
                                ]
                                },   
                                {
                                id: 105,
                                childrenSortList: [],
                                name: '单位5',
                                reportDtoList: [
                                    { 
                                    id: 214,
                                    name: "人员14"
                                    },
                                    { 
                                    id: 215,
                                    name: "人员15"
                                    },
                                    { 
                                    id: 216,
                                    name: "人员16"
                                    }
                                ]
                                },     
                            ],
                            reportDtoList:[]
                            },
                            {
                            id: 13,
                            name: '第二层3',
                            childrenSortList: [
                                {
                                id: 106,
                                name: '第三层4',
                                childrenSortList: [
                                    { 
                                    id: 1061,
                                    name: '单位6', 
                                    childrenSortList:[],
                                    reportDtoList: [
                                        { id: 219, name: '人员19'},
                                        { id: 220, name: '人员20'},
                                    ]
                                    },
                                    { 
                                    id: 1062,
                                    name: '第四层5', 
                                    childrenSortList:[
                                        { 
                                        id: 10621,
                                        name: '单位7',
                                        childrenSortList: [],
                                        reportDtoList: [
                                            { id: 221, name: '人员21'},
                                            { id: 222, name: '人员22'},
                                        ]
                                        },
                                        { 
                                        id: 10622,
                                        name: '单位8',
                                        childrenSortList: [
                                            { 
                                            id: 106221,
                                            name: '单位9', 
                                            childrenSortList: [
                                                { 
                                                id: 1062211,
                                                name: '单位10',
                                                childrenSortList: [],
                                                reportDtoList: [
                                                    { 
                                                    id: 223,
                                                    name: '人员23'
                                                    }
                                                ]
                                                }
                                            ],
                                            reportDtoList: []
                                            }
                                        ],
                                        reportDtoList: []
                                        }
                                    ],
                                    reportDtoList: []
                                    }
                                ],
                                reportDtoList: []
                                }
                            ],
                            reportDtoList: []
                            }
                        ],
                        reportDtoList:[]
                    }
                ]
                const list2 = [
                { id: 10050, parentId: null,  name: 'a1', type: 'mp4', size: null, date: '2021-04-01' },
                { id: 24300, parentId: 10050, name: 'ab', type: 'avi', size: 1024, date: '2020-03-01' },
                { id: 10053, parentId: 24300, name: 'abc', type: 'avi', size: null, date: '2021-04-01' },
                { id: 24330, parentId: 10053, name: 'abcd', type: 'txt', size: 25, date: '2021-10-01' },
                { id: 21011, parentId: 24330, name: 'abcde', type: 'pdf', size: 512, date: '2020-01-01' },
                { id: 22200, parentId: 21011, name: 'test6', type: 'js', size: 1024, date: '2021-06-01' },
                { id: 22201, parentId: 21011, name: 'test7', type: 'js', size: 1024, date: '2021-06-01' },
                { id: 22202, parentId: 21011, name: 'test8', type: 'js', size: 1024, date: '2021-06-01' },
                { id: 23666, parentId: null, name: 'a2', type: 'xlsx', size: 2048, date: '2020-11-01' },
                { id: 23677, parentId: 23666, name: 'a2a', type: 'js', size: 1024, date: '2021-06-01' },
                { id: 23671, parentId: 23677, name: 'test11', type: 'js', size: 1024, date: '2021-06-01' },
                { id: 23672, parentId: 23677, name: 'test12', type: 'js', size: 1024, date: '2021-06-01' },
                { id: 23688, parentId: 23666, name: 'a2b', type: 'js', size: 1024, date: '2021-06-01' },
                { id: 23681, parentId: 23688, name: 'test14', type: 'js', size: 1024, date: '2021-06-01' },
                { id: 23682, parentId: 23688, name: 'test15', type: 'js', size: 1024, date: '2021-06-01' },
                { id: 24555, parentId: null, name: 'a3', type: 'avi', size: 224, date: '2020-10-01' },
                { id: 24566, parentId: 24555, name: 'test16', type: 'js', size: 1024, date: '2021-06-01' },
                { id: 24577, parentId: 24555, name: 'test17', type: 'js', size: 1024, date: '2021-06-01' }
                ]
                const number = Math.round(Math.random()*1500); 
                setTimeout(() => {
                    this.tableData = list2;
                    this.reportLoad = false;
                }, number);
            },
            // 加载子级
            loadChildrenMethod({row}) {
                console.log('row',row);
                let childList = [];
                let childrenSortList = row.childrenSortList || [];
                for(let i = 0;i<childrenSortList.length;i++){
                    childrenSortList[i].isCatalog = false;
                    let directoryNumber = this.countDirectoryNumber(childrenSortList[i])
                    childrenSortList[i].name = childrenSortList[i].name
                    if(directoryNumber==0){
                        childrenSortList.splice(i,1);
                        i=i-1;
                    }
                }
                let reportDtoList = row.reportDtoList || [];
                reportDtoList.forEach((element, idx) => {
                    element.isCatalog = false;
                    element.isCheck = false;
                });

                // childList = reportDtoList.concat(childrenSortList);
                childList = this.formatTreeList(reportDtoList.concat(childrenSortList))
                return new Promise(resolve => {
                    childList.forEach(element => {
                        if (
                            (element.childrenSortList && element.childrenSortList.length > 0)
                            || (element.reportDtoList && element.reportDtoList.length > 0) ) {
                            element.children = [];
                        }
                    });
                    resolve(childList);
                });
            },
		    // 计算目录数量
            countDirectoryNumber(item){   //0
                let count = parseInt(item.quantity) | 0;  // 0  2
                if(item.childrenSortList){
                    item.childrenSortList.forEach((val,index)=>{
                        count += this.countDirectoryNumber(val)   // 0 +  
                    })
                }
                return count;
            },    
            formatTreeList (orgList) {
                // const checkedList = this.propsObj.seletList || [];   //已经选择过的数组
                const checkedList = this.selectAddListOff;   //已经选择过的数组
                let allList = [];
                if (orgList.length > 0) {
                    for (const i in orgList) {
                        orgList[i].isCheck = false;
                        for (const j in checkedList) {
                            if (orgList[i].id == checkedList[j]) {
                                orgList[i].isCheck = true;
                            }
                        }
                    }
                }
                allList = orgList;
                return allList;
            },
            // 设置是否可选
            checCheckboxkMethod({row}) {
                return !row.isCatalog;	//不限层级
                //return row.sortLevel == 5; 层级限制
            },       
            // 选择/取消勾选
            TreeChangeCheckBox( { checked, row } ){
                if (checked) {   //选中
                    if (row.children && row.children.length > 0) {
                        const parentList = [];         //添加父级的id
                        parentList.push(row);   
                        this.getAddproentList(parentList)
                    }else{
                        this.usersList.push(row); 
                        var temp = [];
                        for (var i = 0; i < this.usersList.length; i++){
                            if (temp.indexOf(this.usersList[i]) == -1) {
                                temp.push(this.usersList[i]);
                            }
                        }
                        this.usersList = temp;
                    }         
                }else{
                    if (row.children && row.children.length > 0) {       //删除取消的全选
                        this.setAddproentList(row.children);
                        this.deleteMethod(this.usersList,this.closeList);
                    }else{
                        for (const i in this.usersList) {      //删除取消的行
                            if ( this.usersList[i].id == row.id ) {
                                this.usersList.splice(i,1);
                            }
                        }
                    }
                }
                console.log('原数组',this.usersList)
                console.log('需删数组',this.closeList);
            },
            deleteMethod(list,list2) {   //删除取消的父级全选  
                for (let i = 0; i < list.length; i++) {     
                    for (let j = 0; j < list2.length; j++) {
                        if (list[i].id == list2[j].id) {
                            this.usersList.splice(i,1);
                            this.closeList.splice(j,1);    
                            this.deleteMethod(this.usersList,this.closeList);   
                        }
                    }
                }
            },
            // 确定递归
            getAddproentList(list){
                if (list && list.length > 0) {
                    list.forEach( item =>{
                        if (item.children && item.children.length > 0) {
                            this.getAddproentList(item.children);
                        }else{
                            this.usersList.push(item); 
                            var temp = [];
                            for (var i = 0; i < this.usersList.length; i++){
                                if (temp.indexOf(this.usersList[i]) == -1) {
                                    temp.push(this.usersList[i]);
                                }
                            }
                            this.usersList = temp;
                        }
                    })
                }
            },
            // 取消递归
            setAddproentList(list){
                if (list && list.length > 0) {
                    list.forEach( item =>{
                        if (item.children && item.children.length > 0) {
                            this.setAddproentList(item.children);
                        }else{
                            this.closeList.push(item);  
                        }
                    })
                }
            },
            // 确定
             confirmButton() {
                let moduleIds = "";
                if(this.usersList && this.usersList.length > 0){
                    for (let i = 0; i < this.usersList.length; i++) {
                        if( i == this.usersList.length -1 ) {
                            moduleIds += this.usersList[i].id;
                        }else{
                            moduleIds += this.usersList[i].id + ","
                        }
                    }
                } 
                console.log('选中的',moduleIds);
            },
            // 列样式
			cellClassName() {
				return 'line-height-30';
			},
            // 清空单位名称
			clearSelectWorkName() {
				this.selectWorkName = '';
				this.findOrg();
			},
			// 勾选、取消单位
			changeCheckBox( {row} ) {
				if (!row.isCheck) {
					this.companyid = row.orgId;
				    this.selectWorkName = row.name;
					this.placeholder = row.name;
					this.visible = false;    //关闭弹框
					this.getTree();
				}
			},
            // 选择报表类型
			switchType(){
				this.getTree();
			},
      }
}
</script>

<style scoped>
.toolbar{
    width: 100%;
    padding-top: 10px;
    display: flex;
    justify-content: space-between;
}
.toolbar .toolbar_left {
    width: 50%;
}
.toolbar .toolbar_right {
    width: 47%;
}
</style>
<style>
 .toolbar .toolbar_right .el-input--medium .el-input__inner {
    height: 40px;
    line-height: 40px;
}
</style>